from flask import Flask, render_template, send_from_directory, g
from core import generate_rsa
from core.config import Config
from core.extensions import init_extensions
from api import init_api

app = Flask(__name__, template_folder='templates')
def create_app():

    app.config.from_object(Config)

    # 初始化扩展
    init_extensions(app)

    # 初始化API路由
    init_api(app)

    # 静态文件路由
    @app.route('/static/<path:filename>')
    def static_files(filename):
        return send_from_directory('static', filename)

    @app.route('/db_health')
    def db_health():
        try:
            if not hasattr(g, 'db'):
                return "数据库连接未初始化", 500

            cur = g.db.cursor()
            cur.execute("SELECT 1")
            return "数据库连接正常", 200
        except Exception as e:
            return f"数据库错误: {str(e)}", 500

    return app

create_app()

if __name__ == '__main__':
    import os

    os.makedirs('static/js', exist_ok=True)
    os.makedirs('static/css', exist_ok=True)

    if os.path.exists(generate_rsa.PRIVATE_KEY_PATH):
        os.remove(generate_rsa.PRIVATE_KEY_PATH)
    if os.path.exists(generate_rsa.PUBLIC_KEY_PATH):
        os.remove(generate_rsa.PUBLIC_KEY_PATH)

    generate_rsa.check_rsa_keys()
    app.run(host='0.0.0.0', port=5000, debug=True)